package com.joint.web.action.com;


import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.base.bean.Result;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.joint.base.bean.FlowEnum;
import com.joint.base.entity.*;
import com.joint.base.service.*;
import com.joint.base.service.activiti.WorkflowService;
import com.joint.base.service.activiti.WorkflowTraceService;
import com.joint.base.util.DataUtil;
import com.joint.base.util.EntityConfig;
import com.joint.base.util.FileUtil;
import com.joint.base.util.WorkflowUtils;
import com.joint.core.entity.manage.MeetingLeave;
import com.joint.web.action.BaseAdminAction;
import net.sf.json.JSONObject;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamSource;
import org.springframework.core.io.ResourceLoader;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;
import java.util.zip.ZipInputStream;

/**
 * Created by hpj on 2014/9/16.
 */
@ParentPackage("com")
public class AjaxProcessbriefAction extends BaseAdminAction {

    @Resource
    private UsersService usersService;
    @Resource
    private ProcessBriefService processBriefService;
    @Resource
    private CommonConfigService commonConfigService;

    private CommonConfig creadConfig;
    private CommonConfig ceditConfig;
    private CommonConfig cdocConfig;
    private ProcessBrief processBrief;

    private String rselectType;
    private String eselectType;
    private String dselectType;

    private String archReaderId;
    private String archEditorId;
    private String docReaderId;
    private String processName;
    private String tableKey;

    protected Logger logger = LoggerFactory.getLogger(getClass());

    private static final  EntityConfig entityConfig  = new EntityConfig();

    private List<Map<String,Object>> entityDatas;
    /**
     * 返回流程管理视图
     * @return
     */
    public String list(){
        pager = new Pager();
        /*
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);*/
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);

        /*
        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }*/
        Company com = usersService.getCompanyByUser();
        Users user = usersService.getLoginInfo();
        Map<String,Object> params = new HashMap<String,Object>();
       // params = getSearchFilterParams(_search,params,filters);
        params.put("company",com);
        params.put("state",BaseEnum.StateEnum.Enable);
        pager= processBriefService.findByPager(pager, params);
        List<ProcessBrief>  processBriefList;
        if (pager.getTotalCount() > 0){
            processBriefList = (List<ProcessBrief>) pager.getList();
        }else{
            processBriefList = new ArrayList<>();
        }

        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

        for(ProcessBrief processBrief: processBriefList){
            rMap = new HashMap<String, Object>();
            rMap.put("id", processBrief.getId());
            rMap.put("name", processBrief.getName());
            rMap.put("tableName", entityConfig.getValues(processBrief.getTableKey()));
            rMap.put("creater", processBrief.getCreater() != null ? processBrief.getCreater().getName() : "");
            rMap.put("createDate", DataUtil.DateToString(processBrief.getCreateDate(), "yyyy-MM-dd"));
            rMap.put("state", processBrief.getState().value());
            JSONObject o = JSONObject.fromObject(rMap);
            dataRows.add(o);
        }
        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);
        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records", recordsNum);
        return  ajaxJson(JSONObject.fromObject(data).toString());
    }


    /**
     * 流程简要表新建编辑
     * @return
     */
    public String input() {
        if (StringUtils.isNotEmpty(keyId)) {
            entityDatas = Lists.newArrayList();
            processBrief =  processBriefService.get(keyId);
            List<Map<String,Object>> mapList = entityConfig.getAllProperties();
            Map<String,Object> rmap;
            for(Map map:mapList){
                rmap = Maps.newHashMap();
                rmap.put("key", map.get("key").toString());
                rmap.put("value", map.get("value").toString());
                rmap.put("selected", "");
                if(processBrief.getTableKey()!=null && StringUtils.equals(processBrief.getTableKey(), map.get("key").toString())){
                    rmap.put("selected", "selected");
                }
                entityDatas.add(rmap);
            }
            creadConfig = processBrief.getReadConfig();
            ceditConfig = processBrief.getEditConfig();
            cdocConfig = processBrief.getDocConfig();
            /*
            if (processBrief.getReadConfig() != null) {
                rselectType = processBrief.getReadConfig().getStype();
            }
            if (processBrief.getEditConfig() != null) {
                eselectType = processBrief.getEditConfig().getStype();
            }
            if (processBrief.getDocConfig() != null) {
                dselectType = processBrief.getDocConfig().getStype();
            }*/
        }else{
            entityDatas = entityConfig.getAllProperties();
        }
        return "input";
    }

    /**
     * 流程简要表保存
     * @return
     */
    public String save(){

        if (StringUtils.isNotEmpty(archReaderId)){
            creadConfig = commonConfigService.get(archReaderId);
        }
        if (StringUtils.isNotEmpty(archEditorId)){
            ceditConfig = commonConfigService.get(archEditorId);
        }
        if (StringUtils.isNotEmpty(docReaderId)){
            cdocConfig = commonConfigService.get(docReaderId);
        }
        if(StringUtils.isNotEmpty(keyId)){
            processBrief = processBriefService.get(keyId);
        }else{
            processBrief = new ProcessBrief();
            processBrief.setCreater(usersService.getLoginInfo());
        }
        processBrief.setName(processName);
        processBrief.setTableKey(tableKey);
        processBrief.setDocConfig(cdocConfig);
        processBrief.setReadConfig(creadConfig);
        processBrief.setEditConfig(ceditConfig);
        processBrief.setCompany(usersService.getCompanyByUser());
        if(StringUtils.isNotEmpty(keyId)){
            processBriefService.update(processBrief);
        }else{
            processBriefService.save(processBrief);
        }
        return ajaxHtmlCallback("200", "保存成功！", "操作状态");
    }


    //删除
    public String delete(){
        if(StringUtils.isNotEmpty(keyId)){
            processBrief = processBriefService.get(keyId);
            processBrief.setState(BaseEnum.StateEnum.Delete);
            processBriefService.update(processBrief);
        }
        return  ajaxHtmlCallback("200", "删除成功！","操作状态");
    }

    public CommonConfig getCreadConfig() {
        return creadConfig;
    }

    public void setCreadConfig(CommonConfig creadConfig) {
        this.creadConfig = creadConfig;
    }

    public CommonConfig getCeditConfig() {
        return ceditConfig;
    }

    public void setCeditConfig(CommonConfig ceditConfig) {
        this.ceditConfig = ceditConfig;
    }

    public CommonConfig getCdocConfig() {
        return cdocConfig;
    }

    public void setCdocConfig(CommonConfig cdocConfig) {
        this.cdocConfig = cdocConfig;
    }



    public ProcessBrief getProcessBrief() {
        return processBrief;
    }

    public void setProcessBrief(ProcessBrief processBrief) {
        this.processBrief = processBrief;
    }



    public String getRselectType() {
        return rselectType;
    }

    public void setRselectType(String rselectType) {
        this.rselectType = rselectType;
    }

    public String getEselectType() {
        return eselectType;
    }

    public void setEselectType(String eselectType) {
        this.eselectType = eselectType;
    }

    public String getDselectType() {
        return dselectType;
    }

    public void setDselectType(String dselectType) {
        this.dselectType = dselectType;
    }

    public String getArchReaderId() {
        return archReaderId;
    }

    public void setArchReaderId(String archReaderId) {
        this.archReaderId = archReaderId;
    }

    public String getArchEditorId() {
        return archEditorId;
    }

    public void setArchEditorId(String archEditorId) {
        this.archEditorId = archEditorId;
    }

    public String getDocReaderId() {
        return docReaderId;
    }

    public void setDocReaderId(String docReaderId) {
        this.docReaderId = docReaderId;
    }

    public String getProcessName() {
        return processName;
    }

    public void setProcessName(String processName) {
        this.processName = processName;
    }

    public String getTableKey() {
        return tableKey;
    }

    public void setTableKey(String tableKey) {
        this.tableKey = tableKey;
    }

    public Logger getLogger() {
        return logger;
    }

    public void setLogger(Logger logger) {
        this.logger = logger;
    }


    public List<Map<String, Object>> getEntityDatas() {
        return entityDatas;
    }

    public void setEntityDatas(List<Map<String, Object>> entityDatas) {
        this.entityDatas = entityDatas;
    }
}
